package com.moyun.modelclass.fragment.model;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.moyun.modelclass.activity.LoginVerificationCodeActivity;
import com.moyun.modelclass.activity.ModelDetailsActivity;
import com.moyun.modelclass.activity.ModelShowActivity;
import com.moyun.modelclass.activity.SubmitOrderActivity;
import com.moyun.modelclass.activity.UserInfoActivity;
import com.moyun.modelclass.adapter.ModelDetailsImageAdapter;
import com.moyun.modelclass.adapter.ModelDetailsSurfaceAdapter;
import com.moyun.modelclass.adapter.ParentCommentAdapter;
import com.moyun.modelclass.base.BaseFragment;
import com.moyun.modelclass.dialog.ScanImageDialog;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.AppAddShoppingApi;
import com.moyun.modelclass.http.api.AppHotCommentApi;
import com.moyun.modelclass.http.api.AppModelDetailsApi;
import com.moyun.modelclass.http.api.CheckCommentsLikesApi;
import com.moyun.modelclass.http.api.CommentMakeApi;
import com.moyun.modelclass.http.api.LikeCommentApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.CreateFileUtils;
import com.moyun.modelclass.utils.DataUtil;
import com.moyun.modelclass.utils.GlideEngine;
import com.moyun.modelclass.view.AndroidBugInputBoxAndSoftKeyboard;
import com.moyun.modelclass.view.NonScrollRecyclerView;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


public class ModelDetailFragment extends BaseFragment implements ModelDetailsImageAdapter.OnImageClick, ModelDetailsSurfaceAdapter.OnImageClick, ParentCommentAdapter.OnCommentClick {
    private ImageView ivModelDetailImage;
    private TextView tvModelDetailImageNumber;
    private TextView tvModelDetailTitle;
    private TextView tvModelDetailPrice;
    private TextView tvModelDetailSold;
    private ImageView ivModelDetailHeadPortrait;
    private TextView tvModelDetailName;
    private TextView tvModelDetailTime;
    private TextView tvModelDetailScan;
    private RecyclerView recyclerModelDetailImage;
    private TextView tvModelDetailFileQuantity;
    private RecyclerView recyclerModelDetailFile;
    private TextView tvModelDetailFileContent;
    private TextView modelDetailCommentsNumber;
    private TextView tvModelDetailCheck;
    private NonScrollRecyclerView recyclerModelDetailComments;
    private TextView modelDetailAddShoppingCart;
    private TextView tvModelDetailMake;

    private LinearLayout llModelDetailShoppingAll;
    private RelativeLayout rlModelDetailCommentAll;
    private ImageView ivModelSendImage;
    private EditText etModelContent;
    private TextView tvModelSendContent;
    private FrameLayout flModelPreviewImage;
    private ImageView tvModelPreviewImage;
    private ImageView tvModelPreviewImageDelete;

    private ModelDetailsImageAdapter modelDetailsImageAdapter = new ModelDetailsImageAdapter();
    private ModelDetailsSurfaceAdapter modelDetailsSurfaceAdapter = new ModelDetailsSurfaceAdapter();
    private ParentCommentAdapter parentCommentAdapter = new ParentCommentAdapter();

    private DecimalFormat df = new DecimalFormat("￥##0.00");
    private List<CommentMakeApi.CommentMakeRequest> commentList = new ArrayList<>();
    private File commentImageFile = null;//头像
    private UpdateImageApi.Bean commentImageBean = null;//评论图片
    private String mCommentId = "";//回复评论id
    private String mModelId = "";//模型id

    private String mUserId = "";//作者的userId
    private List<String> modelList = new ArrayList<>();
//    List<File> uriList = new ArrayList<>();

    private List<String> commentIdList = new ArrayList<>();
    private boolean isShowSoftKeyboard = false;

    public static ModelDetailFragment newInstance(String modelId) {
        Bundle args = new Bundle();
        args.putString("modelId", modelId);
        ModelDetailFragment fragment = new ModelDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_model_detail;
    }

    @Override
    protected void assignViews(View view) {
        ivModelDetailImage = (ImageView) view.findViewById(R.id.iv_model_detail_image);
        tvModelDetailImageNumber = (TextView) view.findViewById(R.id.tv_model_detail_image_number);
        tvModelDetailTitle = (TextView) view.findViewById(R.id.tv_model_detail_title);
        tvModelDetailPrice = (TextView) view.findViewById(R.id.tv_model_detail_price);
        tvModelDetailSold = (TextView) view.findViewById(R.id.tv_model_detail_sold);
        ivModelDetailHeadPortrait = (ImageView) view.findViewById(R.id.iv_model_detail_head_portrait);
        tvModelDetailName = (TextView) view.findViewById(R.id.tv_model_detail_name);
        tvModelDetailTime = (TextView) view.findViewById(R.id.tv_model_detail_time);
        tvModelDetailScan = (TextView) view.findViewById(R.id.tv_model_detail_scan);
        recyclerModelDetailImage = (RecyclerView) view.findViewById(R.id.recycler_model_detail_image);
        tvModelDetailFileQuantity = (TextView) view.findViewById(R.id.tv_model_detail_file_quantity);
        recyclerModelDetailFile = (RecyclerView) view.findViewById(R.id.recycler_model_detail_file);
        tvModelDetailFileContent = (TextView) view.findViewById(R.id.tv_model_detail_file_content);
        modelDetailCommentsNumber = (TextView) view.findViewById(R.id.model_detail_comments_number);
        tvModelDetailCheck = (TextView) view.findViewById(R.id.tv_model_detail_check);
        recyclerModelDetailComments = (NonScrollRecyclerView) view.findViewById(R.id.recycler_model_detail_comments);
        modelDetailAddShoppingCart = (TextView) view.findViewById(R.id.model_detail_add_shopping_cart);
        tvModelDetailMake = (TextView) view.findViewById(R.id.tv_model_detail_make);

        llModelDetailShoppingAll = (LinearLayout) view.findViewById(R.id.ll_model_detail_shopping_all);
        rlModelDetailCommentAll = (RelativeLayout) view.findViewById(R.id.rl_model_detail_comment_all);
        ivModelSendImage = (ImageView) view.findViewById(R.id.iv_model_send_image);
        etModelContent = (EditText) view.findViewById(R.id.et_model_content);
        tvModelSendContent = (TextView) view.findViewById(R.id.tv_model_send_content);
        flModelPreviewImage = (FrameLayout) view.findViewById(R.id.fl_model_preview_image);
        tvModelPreviewImage = (ImageView) view.findViewById(R.id.tv_model_preview_image);
        tvModelPreviewImageDelete = (ImageView) view.findViewById(R.id.tv_model_preview_image_delete);

        recyclerModelDetailImage.setLayoutManager(new LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false));
        modelDetailsImageAdapter.setOnImageClick(this);
        recyclerModelDetailImage.setAdapter(modelDetailsImageAdapter);


        recyclerModelDetailFile.setLayoutManager(new LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false));
        modelDetailsSurfaceAdapter.setOnImageClick(this);
        recyclerModelDetailFile.setAdapter(modelDetailsSurfaceAdapter);

        recyclerModelDetailComments.setLayoutManager(new LinearLayoutManager(mContext));
        parentCommentAdapter.setOnCommentClick(this);
        recyclerModelDetailComments.setAdapter(parentCommentAdapter);
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivModelDetailHeadPortrait, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mUserId.isEmpty()) {
                    UserInfoActivity.start(requireActivity(), mUserId);
                }
            }
        });

        //查看全部评论
        ClickUtils.applySingleDebouncing(tvModelDetailCheck, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() != null) {
                    // 调用Activity中的方法
                    ((ModelDetailsActivity) getActivity()).setTabSelect(1);
                }
            }
        });

        //加入购物车
        ClickUtils.applySingleDebouncing(modelDetailAddShoppingCart, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addShoppingLog(modelList);
            }
        });

        //制作
        ClickUtils.applySingleDebouncing(tvModelDetailMake, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    SubmitOrderActivity.start(requireActivity(), modelList);
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                }
            }
        });

        AndroidBugInputBoxAndSoftKeyboard.assistActivity(requireActivity(), true, new AndroidBugInputBoxAndSoftKeyboard.OnChangeListener() {
            @Override
            public void showChange(boolean isShow) {
                if (isShow) {
                    if (CommonConfiguration.isLogin(kv)) {
                        etModelContent.setCursorVisible(true);
                    } else {
//                        ToastUtils.showShort(getContext().getString(R.string.http_token_error));
                        LoginVerificationCodeActivity.start(requireActivity());
                    }
                } else {
                    if (!isShowSoftKeyboard) {
                        llModelDetailShoppingAll.setVisibility(View.VISIBLE);
                        rlModelDetailCommentAll.setVisibility(View.GONE);
                        etModelContent.clearFocus();
                        Glide.with(requireActivity()).clear(tvModelPreviewImage);
                        commentImageBean = null;
                        etModelContent.setText("");
                        flModelPreviewImage.setVisibility(View.GONE);
                    }
                }
            }
        });
        ClickUtils.applySingleDebouncing(tvModelPreviewImageDelete, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Glide.with(requireActivity()).clear(tvModelPreviewImage);
                commentImageBean = null;
                flModelPreviewImage.setVisibility(View.GONE);
            }
        });

        ClickUtils.applySingleDebouncing(tvModelSendContent, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = etModelContent.getText().toString();
                if (!content.isEmpty()) {
                    commentList.clear();
                    CommentMakeApi.CommentMakeRequest comment = new CommentMakeApi.CommentMakeRequest();
                    comment.setCommentContent(content);
                    if (commentImageBean != null) {
                        List<String> image = new ArrayList<>();
                        image.add(commentImageBean.getUrl());
                        comment.setImages(image);
                    }
                    comment.setObjectId(mModelId);
                    comment.setTargetId(mCommentId);
                    commentList.add(comment);
                    initCommentMakeApi(commentList);
                } else {
                    ToastUtils.showShort("请输入评论内容");
                }
            }
        });

        ClickUtils.applySingleDebouncing(ivModelSendImage, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowSoftKeyboard = true;
                KeyboardUtils.hideSoftInput(etModelContent);
                XXPermissions.with(requireActivity()).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                PictureSelector.create(requireActivity())
                                        .openGallery(SelectMimeType.ofImage())
                                        .setImageEngine(GlideEngine.createGlideEngine())
                                        .setMaxSelectNum(1)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(ArrayList<LocalMedia> result) {
                                                for (LocalMedia media : result) {
                                                    Luban.with(requireActivity())
                                                            .load(media.getRealPath())
                                                            .ignoreBy(50)
                                                            .setTargetDir(CreateFileUtils.getSandboxPath(requireActivity()))
                                                            .setCompressListener(new OnCompressListener() {
                                                                                     @Override
                                                                                     public void onStart() {
                                                                                     }

                                                                                     @Override
                                                                                     public void onSuccess(int index, File compressFile) {
                                                                                         commentImageFile = compressFile;
                                                                                         Glide.with(mContext)
                                                                                                 .asBitmap()
                                                                                                 .centerCrop()
                                                                                                 .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
                                                                                                 .placeholder(R.drawable.icon_head_portrait)
                                                                                                 .error(R.drawable.icon_head_portrait)
                                                                                                 .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                                                                                 .into(new BitmapImageViewTarget(tvModelPreviewImage) {
                                                                                                     @Override
                                                                                                     protected void setResource(Bitmap resource) {
                                                                                                         super.setResource(resource);
                                                                                                         tvModelPreviewImage.setImageBitmap(ImageUtils.toRound(resource));
                                                                                                     }
                                                                                                 });
                                                                                         initUpdateImageApi(true);
                                                                                     }

                                                                                     @Override
                                                                                     public void onError(int index, Throwable e) {
                                                                                         ToastUtils.showShort("选择图片失败");
                                                                                     }
                                                                                 }
                                                            ).launch();
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                ToastUtils.showShort("获取存储权限失败");
                            }
                        });
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
        mModelId = bundle.getString("modelId", "");
        if (mModelId != null && !mModelId.isEmpty()) {
            modelList.add(mModelId);
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        iniModelDetailsLog();
        initCommentsLog();
    }

    private void initUpdateImageApi(boolean isWatermark) {
        isShowSoftKeyboard = false;
        EasyHttp.post(this).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(commentImageFile)
                        .setWatermark(isWatermark))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                        flModelPreviewImage.setVisibility(View.VISIBLE);
                        commentImageBean = result.getData();
                    }
                });
    }

    private void initCommentMakeApi(List<CommentMakeApi.CommentMakeRequest> commentList) {
        EasyHttp.post(this).api(new CommentMakeApi().setType(2).setCommentObjectList(commentList))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        mCommentId = "";
                        initCommentsLog();
                        ToastUtils.showShort("回复成功");
                        llModelDetailShoppingAll.setVisibility(View.VISIBLE);
                        rlModelDetailCommentAll.setVisibility(View.GONE);
                        KeyboardUtils.hideSoftInput(mActivity);
                        etModelContent.clearFocus();
                        Glide.with(requireActivity()).clear(tvModelPreviewImage);
                        commentImageBean = null;
                        etModelContent.setText("");
                        flModelPreviewImage.setVisibility(View.GONE);
                    }
                });
    }

    //模型详情
    private void iniModelDetailsLog() {
        if (mModelId == null || mModelId.isEmpty()) {
            ToastUtils.showShort("模型id为空");
            return;
        }
        EasyHttp.post(requireActivity())
                .api(new AppModelDetailsApi().setArticleId(mModelId))
                .request(new HttpCallback<HttpData<AppModelDetailsApi.Bean>>(this) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(HttpData<AppModelDetailsApi.Bean> result) {
                        if (result != null && result.getData() != null) {
                            mUserId = result.getData().getCreateUser();
                            Glide.with(requireActivity())
                                    .load(CommonConfiguration.splitResUrl(3, result.getData().getCoverImage()))
                                    .fitCenter()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .into(ivModelDetailImage);
                            tvModelDetailTitle.setText(result.getData().getTitle());
                            tvModelDetailPrice.setText(df.format(result.getData().getPrice() * 0.01));
                            tvModelDetailSold.setText("已售 " + result.getData().getSaleCount());

                            Glide.with(requireActivity())
                                    .asBitmap()
                                    .load(CommonConfiguration.splitResUrl(3, result.getData().getCreateUserAvatar()))
                                    .placeholder(R.drawable.icon_head_portrait)
                                    .error(R.drawable.icon_head_portrait)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                    .into(new BitmapImageViewTarget(ivModelDetailHeadPortrait) {
                                        @Override
                                        protected void setResource(Bitmap resource) {
                                            super.setResource(resource);
                                            ivModelDetailHeadPortrait.setImageBitmap(ImageUtils.toRound(resource));
                                        }
                                    });
                            tvModelDetailImageNumber.setText("编号：" + result.getData().getModelNo());
                            tvModelDetailName.setText(result.getData().getNickName());
                            tvModelDetailTime.setText(DataUtil.getTimeShowString(TimeUtils.string2Millis(result.getData().getUpdateTime()), false) + "发布");
                            tvModelDetailScan.setText("浏览" + result.getData().getScanCount());
                            if (result.getData().getImages() != null && result.getData().getImages().size() > 0) {
                                modelDetailsImageAdapter.setList(result.getData().getImages());
                            }

                            tvModelDetailFileContent.setText(result.getData().getDesc());

                            int stlNum = 0;
                            if (result.getData().getOneStlPieces() != null && result.getData().getOneStlPieces().size() > 0) {
                                stlNum = stlNum + result.getData().getOneStlPieces().size();
                                modelDetailsSurfaceAdapter.setList(result.getData().getOneStlPieces());
                            }
                            if (result.getData().getStlFiles() != null && result.getData().getStlFiles().size() > 0) {
                                stlNum = stlNum + result.getData().getStlFiles().size();
                                modelDetailsSurfaceAdapter.addData(result.getData().getStlFiles());
                            }

                            tvModelDetailFileQuantity.setText(stlNum + "个文件");
                        }
                    }
                });
    }


    //评论
    private void initCommentsLog() {
        if (mModelId == null || mModelId.isEmpty()) {
            ToastUtils.showShort("模型id为空");
            return;
        }
        EasyHttp.post(requireActivity())
                .api(new AppHotCommentApi().setType(2).setObjectId(mModelId))
                .request(new HttpCallback<HttpData<AppHotCommentApi.Bean>>(this) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(HttpData<AppHotCommentApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getComments().size() > 0) {
                            modelDetailCommentsNumber.setText("评论   " + result.getData().getTotalComment());
                            parentCommentAdapter.setList(result.getData().getComments());
                        } else {
                            modelDetailCommentsNumber.setText("评论   0");
                            parentCommentAdapter.setEmptyView(R.layout.empty_comment_layout);
                        }

                        if (result != null && result.getData() != null && result.getData().getComments().size() > 0) {
                            for (int i = 0; i < result.getData().getComments().size(); i++) {
                                commentIdList.add(result.getData().getComments().get(i).getId());
                                if (result.getData().getComments().get(i).getChildren() != null && result.getData().getComments().get(i).getChildren().size() > 0) {
                                    for (int j = 0; j < result.getData().getComments().get(i).getChildren().size(); j++) {
                                        commentIdList.add(result.getData().getComments().get(i).getChildren().get(j).getId());
                                    }
                                }
                            }
                        }
                        checkComments();
                    }
                });
    }

    private void checkComments() {
        if (CommonConfiguration.isLogin(kv)) {
            EasyHttp.post(this)
                    .api(new CheckCommentsLikesApi().setCommentIdList(commentIdList))
                    .request(new HttpCallback<HttpData<CheckCommentsLikesApi.Bean>>(this) {
                        @Override
                        public void onSucceed(HttpData<CheckCommentsLikesApi.Bean> result) {
                            if (result != null && result.getData() != null && result.getData().getLikes().size() > 0) {
                                parentCommentAdapter.setZanState(result.getData().getLikes());
                            }
                        }
                    });
        }
    }

    //加入购物车
    private void addShoppingLog(List<String> buyList) {
        if (buyList.size() == 0) {
            ToastUtils.showShort("模型id列表为空");
            return;
        }
        EasyHttp.post(requireActivity())
                .api(new AppAddShoppingApi().setModelIdList(buyList))
                .request(new HttpCallback<HttpData<AppAddShoppingApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<AppAddShoppingApi.Bean> result) {
                        ToastUtils.showShort("加入购物车成功");
                    }
                });
    }

    @Override
    public void zan(String commentId, boolean isLike) {
        EasyHttp.post(requireActivity())
                .api(new LikeCommentApi().setCommentId(commentId).setLikes(isLike))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
//                        initCommentsLog();
                    }
                });
    }

    @Override
    public void replay(String commentId) {
        this.mCommentId = commentId;
        llModelDetailShoppingAll.setVisibility(View.GONE);
        rlModelDetailCommentAll.setVisibility(View.VISIBLE);
        KeyboardUtils.showSoftInput(mActivity);
        etModelContent.requestFocus();
    }

    @Override
    public void showImage(String imageUrl) {
        if (CommonConfiguration.isLogin(kv)) {
            ScanImageDialog.getInstance(mContext, imageUrl).builder().setNegativeButton().show();
        } else {
            LoginVerificationCodeActivity.start(requireActivity());
        }
    }

    @Override
    public void showStl(AppModelDetailsApi.StlFilesBean beanInfo) {
        ModelShowActivity.start(requireActivity(), beanInfo.getFileId(), beanInfo.getFile(), beanInfo.getXyz(), beanInfo.getRemark(),beanInfo.isNeedReGetThumbnail());
//        ScanStlDialog.getInstance(requireActivity(), beanInfo).builder().setNegativeButton().show();
    }
}
